<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Closure;
use Illuminate\Http\Response;

class Authenticate extends Middleware
{
  private $unauthorizedResponse = [
    'success' => false,
    'status' => Response::HTTP_UNAUTHORIZED,
    'message' => 'Unauthorized',
  ];

  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @param  string[]  ...$guards
   * @return mixed
   *
   * @throws \Illuminate\Auth\AuthenticationException
   */
  public function handle($request, Closure $next, ...$guards)
  {

    if ($this->auth->guard($guards[0])->guest()) {
      return response()->json(
        $this->unauthorizedResponse,
        $this->unauthorizedResponse['status']
      );
    }

    $this->authenticate($request, $guards);

    return $next($request);
  }
}
